from core.memory.memory_handler import MemoryHandler
import pandas as pd
from core.utils.logging_handler import LoggingHandler

class SessionManager:
    def __init__(self):
        self.logger = LoggingHandler().get_logger()
        self.logger.info("初始化 SessionManager")
        self.conversation_history = []
        self.memory_handler = MemoryHandler()

        # 加载之前保存的会话历史
        saved_history = self.memory_handler.get_memory("conversation_history")
        if saved_history:
            self.conversation_history = saved_history

    def add_to_history(self, user_input, generated_code=None, execution_result=None, natural_language_response=None, summary=None):
        """将用户输入、模型响应、执行结果和总结添加到对话历史中。"""
        history_entry = {"user_input": user_input}

        if generated_code is not None:
            history_entry["generated_code"] = generated_code
        if execution_result is not None:
            history_entry["execution_result"] = execution_result
        if natural_language_response is not None:
            history_entry["model_response"] = natural_language_response
        if summary is not None:
            history_entry["summary"] = summary

        self.logger.info(f"添加到历史记录: {user_input}")
        self.conversation_history.append(history_entry)

    def get_conversation_history(self):
        """返回当前的对话历史。"""
        return self.conversation_history

    def clear_history(self):
        """清除对话历史。"""
        self.conversation_history = []
        self.memory_handler.update_memory("conversation_history", self.conversation_history)

    def format_for_model(self):
        """将对话历史格式化为字符串，以传递给模型。"""
        formatted_history = ""
        for entry in self.conversation_history:
            formatted_history += f"User: {entry['user_input']}\n"
            if 'model_response' in entry:
                formatted_history += f"Model: {entry['model_response']}\n"
            if 'execution_result' in entry:
                formatted_history += f"Execution Result: {entry['execution_result']}\n"
            if 'generated_code' in entry:
                formatted_history += f"Generated Code: {entry['generated_code']}\n"
            if 'summary' in entry:
                formatted_history += f"Summary: {entry['summary']}\n"
        return formatted_history

    def save_memory(self):
        """保存当前对话历史到记忆中。"""
        self.logger.info("保存对话历史到记忆中")
        self.memory_handler.update_memory("conversation_history", self.conversation_history)



